package org.example.xml;

import com.alibaba.druid.support.logging.Resources;
import lombok.extern.slf4j.Slf4j;
import org.example.builder.BaseBuilder;
import org.example.config.Configuration;
import org.example.parse.XPathParser;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder extends BaseBuilder {

    //mapper资源文件
    private String resource;
    private XPathParser xPathParser;

    private String namespace;

    public XMLMapperBuilder(InputStream resourceAsStream, Configuration configuration,String resource) {
        super(configuration);
        this.xPathParser = new XPathParser(resourceAsStream);
        this.resource   = resource;
    }

    //解析
    public void parse() {
        //解析mapper文件
        XNode node = xPathParser.evalNode("/mapper");
        //命名空间
        String namespace = node.getStringAttribute("namespace");
        this.namespace = namespace;
        //处理命名空间
        bindMapperForNamespace(namespace);
        //解析SQL
        List<XNode> xNodes = node.evalNodes("select"); //"select|insert|update|delete"
        //构建SQL
        buildStatementFromContext(xNodes);
    }

    private void bindMapperForNamespace(String namespace)  {
        Class<?> boundType = null;
        try {
            boundType = Resources.classForName(namespace);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("namespace找不到");
        }
        configuration.addMapper(boundType);
    }

    private void buildStatementFromContext(List<XNode> list) {
        for (XNode context : list) {
            final XMLStatementBuilder statementParser = new XMLStatementBuilder(configuration, context,resource,namespace);
            try {
                statementParser.parse();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
